﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Press.MVC.Data;
using Press.MVC.Services;

namespace Press.MVC.Web.Controllers
{
    [Authorize(Roles = "BlogAdmin")] //TODO Change role here to BlogAdmin TODO User Authorization on per blog basis. 
    public class BlogAdminController : BaseController
    {
        #region Constructor
        IBlogService _blogService;
        IUserService _userService;

        public BlogAdminController(IBlogService blogService, IUserService userService) 
        {
            _blogService = blogService;
            _userService = userService;
        }

        #endregion

        /// <summary>
        /// Index - Shows the Blog Admin Dashboard 
        /// </summary>
        /// <returns></returns>        
        public ActionResult Index(string blogname)
        {
            ViewData["Title"] = "Blog Admin Home";
            ViewData["Message"] = "TODO";

            return View("Index");
        }

        /// <summary>
        /// PostList - Shows the Post Listing
        /// </summary>
        /// <returns></returns>
        public ActionResult PostList(string blogname)
        {
            ViewData["Title"] = "Blog Admin Home - Manage Posts";
            ViewData["Message"] = "TODO";
            
            ViewData["CurrentSection"] = "manage"; // We need a better way to do this. 
            ViewData["CurrentPage"] = "PostList"; // We need a better way to do this. 

            BlogData bdata = new BlogData();
            bdata.Blog = _blogService.GetBlog(blogname); 

            return View("PostList",bdata);
        }

        /// <summary>
        /// PostNew - Shows Post New 
        /// </summary>
        /// <returns></returns>
        public ActionResult PostNew(string blogname)
        {
            ViewData["Title"] = "Blog Admin Home - Manage Posts";
            ViewData["Message"] = "TODO";

            ViewData["CurrentSection"] = "write"; // We need a better way to do this. 
            ViewData["CurrentPage"] = "PostNew"; // We need a better way to do this. 

            BlogData bdata = new BlogData();
            bdata.Blog = _blogService.GetBlog(blogname);
            bdata.PostCategories = _blogService.GetPostCategories(_blogService.GetBlog(blogname).ID);

            return View("PostNew",bdata);
        }

        public ActionResult PostNewSave()
        {
            Press.MVC.Data.Post p = new Post();
            p.Title = Request.Form["Title"];
            p.Summary = Request.Form["Summary"];
            p.Body = Request.Form["Body"];
            p.AllowComments = Convert.ToBoolean(Request.Form["AllowComments"].ToString() );
            p.Timestamp = DateTime.Now;
            p.BlogId = Convert.ToInt32(Request.Form["blogid"]);
            p.PostCategoryID = Convert.ToInt32( this.ReadFromRequest("categoryId") );

            _blogService.SavePost(p);

            return RedirectToAction("PostList","BlogAdmin");
        }

        

        /// <summary>
        /// PostEdit - Shows Post Edit 
        /// </summary>
        /// <returns></returns>
        public ActionResult PostEdit(int postId)
        {
            BlogData bdata = new BlogData();
            bdata.Post = _blogService.GetPost(postId);

            bdata.PostCategories = _blogService.GetPostCategories(_blogService.GetPost(postId).BlogId);
            return View("PostEdit", bdata);
        }

        /// <summary>
        /// PostList - Save post
        /// </summary>
        /// <returns></returns>
        public ActionResult PostSave()
        {
            Press.MVC.Data.Post p = new Post();
            p.Title = Request.Form["Title"];
            p.Summary = Request.Form["Summary"];
            p.Body = Request.Form["Body"];
            //p.AllowComments = Convert.ToBoolean(Request.Form["AllowComments"].ToString());
            p.Timestamp = DateTime.Now;
            p.BlogId = Convert.ToInt32(Request.Form["blogid"]);
            p.PostCategoryID = Convert.ToInt32(Request.Form["postCategoryId"]);
            p.ID = Convert.ToInt32(Request.Form["postid"]);
            _blogService.SavePost(p);            

            return RedirectToAction("PostList", "BlogAdmin");
        }

        /// <summary>
        /// PostDelete - Delete post
        /// </summary>
        /// <returns></returns>
        public ActionResult PostDelete()
        {   
            string[] arPostId =  Request.Form["postid"].Split(",".ToCharArray());

            if (arPostId.Length > 0)
            {
                foreach (string item in arPostId)
                {
                    _blogService.DeletePost(Convert.ToInt32(item));
                }
            }

            return RedirectToAction("PostList", "BlogAdmin");
        }

        /// <summary>
        /// PostCategoryList - Shows the Post Category Listing 
        /// </summary>
        /// <returns></returns>
        public ActionResult PostCategoryList(string blogname)
        {
            ViewData["Title"] = "Blog Admin Home - Manage Post Categories";
            ViewData["Message"] = "TODO";

            ViewData["CurrentSection"] = "manage"; // TODO We need a better way to do this. 
            ViewData["CurrentPage"] = "PostCategoryList"; // TODO We need a better way to do this. 

            BlogData bdata = new BlogData();
            bdata.Blog = _blogService.GetBlog(blogname);
            bdata.PostCategories = _blogService.GetPostCategories(_blogService.GetBlog(blogname).ID);

            return View("PostCategoryList", bdata);
        }

        /// <summary>
        /// PostCategoryEdit - Shows the Post Category Edit
        /// </summary>
        /// <returns></returns>
        public ActionResult PostCategoryEdit(int postCategoryId)
        {
            ViewData["Title"] = "Blog Admin Home - Manage Post Category Item";
            ViewData["Message"] = "TODO";
            BlogData bdata = new BlogData();
            bdata.PostCategory = _blogService.GetPostCategory(postCategoryId);

            return View("PostCategoryEdit",bdata);
        }

        /// <summary>
        /// PostCategorySave - Save the Post Category
        /// </summary>
        /// <returns></returns>
        public ActionResult PostCategorySave()
        {
            int postCatId = 0;

            if( Request.Form["postcategoryid"] != null && Request.Form["postcategoryid"].Length > 0)
            {
                postCatId = Convert.ToInt32(Request.Form["postcategoryid"]);
            }
            Press.MVC.Data.PostCategory pc = new PostCategory();
            pc.Name = Request.Form["CategoryName"];
            if (postCatId != 0)
            {
                pc.ID = postCatId;
            }
            pc.BlogId = Convert.ToInt32(Request.Form["blogid"]);
            _blogService.SavePostCategory(pc);
            return RedirectToAction("PostCategoryList", "BlogAdmin");
        }

        /// <summary>
        /// PostCategoryDelete - Delete the Post Category
        /// </summary>
        /// <returns></returns>
        public ActionResult PostCategoryDelete()
        {
            ViewData["Title"] = "Blog Admin Home - Manage Posts";
            ViewData["Message"] = "TODO";

            return View("Index");
        }

        /// <summary>
        /// TagList - Shows the Tag Listing
        /// </summary>
        /// <returns></returns>
        public ActionResult TagList()
        {
            ViewData["Title"] = "Blog Admin Home - Manage Tags";
            ViewData["Message"] = "TODO";
            ViewData["CurrentSection"] = "manage"; // We need a better way to do this. 
            ViewData["CurrentPage"] = "TagList";

            return View("TagList");
        }

        /// <summary>
        /// TagEdit - Shows Tag Edit 
        /// </summary>
        /// <returns></returns>
        public ActionResult TagEdit()
        {
            ViewData["Title"] = "Blog Admin Home - Manage Posts";
            ViewData["Message"] = "TODO";

            return View("TagEdit");
        }

        /// <summary>
        /// TagList - Save tag
        /// </summary>
        /// <returns></returns>
        public ActionResult TagSave()
        {
            ViewData["Title"] = "Blog Admin Home - Manage Posts";
            ViewData["Message"] = "TODO";

            //TODO return RedirectToAction

            return View("Index");
        }

        /// <summary>
        /// TagDelete - Delete tag
        /// </summary>
        /// <returns></returns>
        public ActionResult TagDelete()
        {
            ViewData["Title"] = "Blog Admin Home - Manage Posts";
            ViewData["Message"] = "TODO";

            //TODO return RedirectToAction

            return View("Index");
        }

        /// <summary>
        /// OnActionExecuting - Check if the current user has access to the current Blog Dashboard.
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            RouteData routeData = filterContext.RouteData;
            RouteValueDictionary routeValues = routeData.Values;

            string currentBlogName = "";
            int currentBlogId = 0;

            // Check which blog admin site they are trying to access
            // Store the blog admin site they are trying to access
            foreach (string key in routeValues.Keys)
            {
               if (key == "blogname")
               {
                   currentBlogName = routeValues[key].ToString();
               }               
            }

            // Check if the user has access to this Blog Admin Site.
            // Get which blog(s) the user owns and is therefore a Blog "Admin" for the Blog. The user may be a Blog Admin for more than one blog.

            Blog b = _blogService.GetBlog(currentBlogName);
            if (b != null)
            {
                bool doesUserHaveAdminAccess = _userService.HasAdminAccessToBlog(b.ID, AppHelper.GetUserName());

                // If the user is not the Blog "Admin" for the requested Blog Admin site then Cancel this action
                // and send the user to the Unauthorized Blog Access Url.
                // For now we will send them an unauthorized exception.
                if (!doesUserHaveAdminAccess)
                {
                    string sUnauthorizedBlogAccessUrl = "";
                    //TODO add in unauthorized page. filterContext.HttpContext.Response.Redirect(sUnauthorizedBlogAccessUrl, true);
                    filterContext.Cancel = true;
                    throw new InvalidOperationException("You are not authorized to view this Blog Dashboard. TODO redirect the user to somewhere nice.");
                }

                //FOR TESTING filterContext.HttpContext.Response.Write("currentBlogName" + currentBlogName + "ID from service: " + blogid.ToString() );
                //FOR TESTING filterContext.Cancel = true;
            }
            else // The blog can't be loaded. Send the user to a msg saying the url is not found. Possibly the user is modifying the url and entered a blogname that does not exist
            {
                filterContext.Cancel = true;
                throw new InvalidOperationException("The Blog Dashboard at the location specified does not exist. TODO redirect the user to somewhere nice.");
            }
           
            base.OnActionExecuting(filterContext);
       }

    }
}
